<template>
  <div>
    <el-card class="box-card" shadow="hover">
      <!-- 搜索表单-->
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="订单量" prop="roleName">
          <el-input-number
            v-model="queryParams.minOrderCount"
            style="width: 150px"
            controls-position="right"
            :min="0"
            :precision="2"
            :step="0.1"
            size="small"
          />
          <span>~</span>
          <el-input-number
            v-model="queryParams.maxOrderCount"
            style="width: 150px"
            controls-position="right"
            :min="0"
            :precision="2"
            :step="0.1"
            size="small"
          />
        </el-form-item>
        <el-form-item label="投放地址" prop="roleKey">
          <el-cascader
            v-model="queryParams.address"
            size="small"
            :options="options"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="设备状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="设备状态"
            clearable
            size="small"
            style="width: 240px"
          >
            <el-option
              v-for="statu in statusOptions"
              :key="statu.value"
              :label="statu.label"
              :value="statu.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="投放时间">
          <el-date-picker
            v-model="date"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
          <el-button
            icon="el-icon-plus"
            size="mini"
            @click="
              (dialogVisible = true),
                (dialogTitle = '添加设备'),
                (form = {}),
                (img = false)
            "
            type="primary"
          >
            添加设备
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        @expand-change="expandSelect"
        :row-key="getRowKeys"
        :expand-row-keys="expands"
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column type="expand" label="修改价格">
          <template slot-scope="props">
            <el-table
              :span-method="objectOneMethod"
              :data="priceTableData"
              :header-cell-style="{ background: '#409EFF', color: '#fff' }"
            >
              <el-table-column align="center">
                <template slot="header">
                  <span>设备编号：{{ props.row.code }}</span>
                  <span
                    style="position: relative; cursor: pointer; float: right"
                    @click="submmitPrice(props.row.code)"
                    ><i class="el-icon-upload2" />提交</span
                  >
                </template>
                <el-table-column prop="type" label="打印类型" align="center">
                  <template slot-scope="scope">
                    <el-select
                      v-model="scope.row.type"
                      placeholder="打印类型"
                      clearable
                      size="small"
                      style="width: 240px"
                    >
                      <el-option
                        v-for="statu in printOptions"
                        :key="statu.value"
                        :label="statu.label"
                        :value="statu.value"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="paperNumber"
                  label="纸张范围"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-input-number
                      :min="0"
                      :precision="2"
                      :step="1"
                      size="small"
                      v-model="scope.row.paperNumber"
                      style="width: 150px"
                    />
                    <span>张以内</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="blackAndWhite"
                  label="黑白"
                  align="center"
                >
                  <template slot-scope="scope">
                    <span>￥：</span>
                    <el-input-number
                      controls-position="right"
                      :min="0"
                      :precision="2"
                      :step="0.1"
                      size="small"
                      v-model="scope.row.noColorPrice"
                      style="width: 150px"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="color" label="彩色" align="center">
                  <template slot-scope="scope">
                    <span>￥：</span>
                    <el-input-number
                      controls-position="right"
                      :min="0"
                      :precision="2"
                      :step="0.1"
                      size="small"
                      v-model="scope.row.colorPrice"
                      style="width: 150px"
                    />
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" align="center">
                  <template slot-scope="scope">
                    <i
                      class="el-icon-plus"
                      style="font-size: 12px; color: #409eff; cursor: pointer"
                      @click="addPrice(scope.row)"
                      >增加</i
                    >
                    <i
                      class="el-icon-minus"
                      style="font-size: 12px; color: #f56c6c; cursor: pointer"
                      @click="
                        removePrice(
                          scope.row.colorId,
                          scope.row.noColorId,
                          scope.$index,
                          scope.row.default
                        )
                      "
                      >删除</i
                    >
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="id" align="center"> </el-table-column>
        <el-table-column prop="name" label="设备名称" align="center">
        </el-table-column>
        <el-table-column prop="qrCodeUrl" label="设备二维码" align="center">
          <template slot-scope="scope">
            <img
              v-if="scope.row.qrCodeUrl"
              :src="scope.row.qrCodeUrl"
              class="url"
            />
          </template>
        </el-table-column>
        <el-table-column prop="code" label="设备编号" align="center">
        </el-table-column>
        <el-table-column prop="position" label="投放区域" align="center">
        </el-table-column>
        <el-table-column prop="positionDetails" label="详细地址" align="center">
        </el-table-column>
        <el-table-column prop="statusValue" label="设备状态" align="center">
        </el-table-column>
        <el-table-column prop="orderCount" label="订单量" align="center">
        </el-table-column>
        <el-table-column
          prop="putDate"
          label="投放日期"
          width="100px"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="leader" label="投放区域负责人" align="center">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220" align="center">
          <template slot-scope="scope">
            <i
              class="el-icon-tools"
              style="font-size: 12px; color: #409eff; cursor: pointer"
              @click="setTools(scope.row.code)"
              >设置分账成员</i
            >
            <i
              class="el-icon-edit"
              style="font-size: 12px; color: #409eff; cursor: pointer"
              @click="updateDevice(scope.row.id)"
              >编辑</i
            >
            <i
              class="el-icon-setting"
              style="font-size: 12px; color: #f56c6c; cursor: pointer"
              @click="reset(scope.row.code)"
              v-hasPermi="['app_pages:device:reset']"
              >清零</i
            >
            <i
              class="el-icon-delete"
              style="font-size: 12px; color: #f56c6c; cursor: pointer"
              @click="remove(scope.row.id)"
              v-hasPermi="['app_pages:device:del']"
              >删除</i
            >
          </template>
        </el-table-column>
      </el-table>
      <!--分页栏-->
      <el-pagination
        background
        align="center"
        @size-change="handleSizeChange($event, 111)"
        @current-change="data()"
        :current-page.sync="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 设置分账成员 -->
    <el-dialog
      title="设置分账成员"
      :visible.sync="setSeparateVisible"
      width="50%"
    >
      <el-form :model="sepForm" label-width="120px" style="margin-top: 20px">
        <el-form-item label="分账用户">
          <el-select
            v-model="sepForm.saId"
            style="margin-left: 20px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in separates"
              :key="item.id"
              :label="item.identityName"
              :value="item.id"
              :disabled="getDisabled(item.id)"
            >
            </el-option>
          </el-select>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <el-input-number
            v-model="sepForm.scale"
            :controls="false"
            :min="0"
            placeholder="请输入分账比例（百分比）"
          ></el-input-number>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <el-button
            type="primary"
            :loading="addHeaderLoad"
            @click="addSeparatUser"
            >新增</el-button
          >
        </el-form-item>

        <el-form-item prop="startTime" label="已添加成员：">
          <el-tag
            :key="index"
            v-for="(item, index) in facSeparateList"
            closable
            :disable-transitions="false"
            style="margin-left: 20px"
            @close="deleteSeparate(item)"
          >
            {{ item.merchantName }}（{{ item.scale }}%）
          </el-tag>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--经销商添加框/编辑框-->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" label-width="140px" :rules="rules">
        <el-form-item label="广告缩略图">
          <el-upload
            class="Device-uploader"
            :action="uploadUrl"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleDeviceSuccess"
            :before-upload="beforeDeviceUpload"
          >
            <img v-if="img" :src="form.litimgUrl" class="Device" />
            <i v-else class="el-icon-plus Device-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="设备二维码">
          <el-upload
            class="Device-uploader"
            :action="uploadUrl"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleqrCodeSuccess"
            :before-upload="beforeDeviceUpload"
          >
            <img v-if="img" :src="form.qrCodeUrl" class="Device" />
            <i v-else class="el-icon-plus Device-uploader-icon"></i>
          </el-upload>
        </el-form-item>
		<el-form-item label="用户名称">
			<el-select
				    v-model="form.userId"
				    placeholder="用户名称-所属部门"
				    clearable
					filterable
				    style="width: 100%"
				  >
				    <el-option
				      v-for="statu in userIdOptions"
				      :key="statu.userId"
				      :label="statu.dept?statu.nickName+'-'+statu.dept.deptName:statu.nickName "
				      :value="statu.userId"
				    />
			</el-select>
		</el-form-item>
        <el-form-item label="设备编号">
          <el-input v-model="form.code"></el-input>
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="设备投放省市区">
          <el-cascader
            :options="options"
            style="width: 100%"
            v-model="addressList"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="投放详细地址">
          <el-input v-model="form.positionDetails"></el-input>
        </el-form-item>
        <el-form-item label="投放地负责人姓名">
          <el-input v-model="form.leader"></el-input>
        </el-form-item>
        <el-form-item label="投放地负责人电话" prop="leaderPhone">
          <el-input v-model="form.leaderPhone"></el-input>
        </el-form-item>
        <el-form-item label="设备状态">
          <el-select
            v-model="form.status"
            placeholder="设备状态"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="statu in statusOptions"
              :key="statu.value"
              :label="statu.label"
              :value="statu.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { regionData, CodeToText } from "element-china-area-data";
import {
  list,
  add,
  del,
  update,
  device,
  inquire,
  priceList,
  printType,
  addPrintPrice,
  delPrintPrice,
  defaultPrintingPrice,
  separateList,
  facSeparateList,
  addSeparateUser,
  deleteSeparateUser,
  facilityreset,
} from "@/api/app_pages/device";
import { listUser  } from "@/api/system/user";
import { getToken } from "@/utils/auth";
import { getDicts } from "@/api/system/dict/data";
export default {
  components: {},
  data() {
    return {
      queryParams: {},
      options: regionData,
      tableData: [],
      size: 20,
      currentPage: 1,
      total: 0,
      dialogVisible: false,
      form: {},
      dialogTitle: "添加设备",
      deviceImageUrl: "",
      statusOptions: [],
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      img: false,
      priceTableData: [{}],
      getRowKeys(row) {
        return row.id;
      },
      expands: [],
      printOptions: [],
      separates: [],
      code: null,
      // 表单校验
      rules: {
        leaderPhone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      date: [],
      setSeparateVisible: false,
      facSeparateList: [],
      sepForm: { facId: "" },
      addHeaderLoad: false,
      addressList: [],
	  userIdOptions:[]
    };
  },
  created() {
    getDicts("fac_facility_status").then((res) => {
      let data = [];
      res.data.forEach((item) => {
        data.push({ label: item.dictLabel, value: item.dictValue });
      });
      this.statusOptions = data;
    });
    printType().then((res) => {
      res.rows.forEach((item) => {
        this.printOptions.push({ label: item.type, value: item.code });
      });
    });
    separateList({state:1}).then((res) => {
      if (res.code === 200) this.separates = res.data;
    });
	listUser( {pageNum: 1,pageSize: 9999}).then(response => {
	    this.userIdOptions = response.rows;
	  });
    this.data();
  },
  methods: {
    deleteSeparate(item) {
      const _this = this;
      this.$confirm("确定删除该分账用户？").then(() => {
        deleteSeparateUser({ facId: item.facId, saId: item.saId }).then(
          (res) => {
            if (res.code !== 200) return _this.$message.error(res.msg);
            _this.setTools(item.facId);
          }
        );
      });
    },
    getDisabled(id) {
      return this.facSeparateList.filter((fac) => fac.saId == id).length > 0;
    },
    addSeparatUser() {
      if(!this.sepForm.saId){
         this.$message.error("请选择分账用户!");
        return
      }
      if(!this.sepForm.scale){
         this.$message.error("请输入分账比例（百分比）!");
        return
      }
      const _this = this;
      addSeparateUser(this.sepForm).then((res) => {
        if (res.code !== 200) return _this.$message.error(res.msg);
        _this.setTools(_this.sepForm.facId);
        // _this.sepForm = {};
      });
    },
    data() {
      list(this.size, this.currentPage).then((res) => {
        this.tableData = res.rows;
        for (let i = 0; i < res.rows.length; i++) {
          this.tableData[i].position =
            CodeToText[res.rows[i].positionProvince] +
            "/" +
            CodeToText[res.rows[i].positionCity] +
            "/" +
            CodeToText[res.rows[i].positionArea];
          //this.tableData[i].qrCodeUrl =  process.env.VUE_APP_BASE_API + res.rows[i].qrCodeUrl
        }
        this.total = parseInt(res.total);
      });
    },
    setTools(id) {
      this.sepForm = {}
      const _this = this;
      _this.sepForm.facId = id;
      facSeparateList(id).then(function (res) {
        if (res.code !== 200) return _this.$message.error(res.msg);
        _this.setSeparateVisible = true;
        _this.facSeparateList = res.data.map((dt) => {
          let sep = _this.separates.filter((tes) => dt.saId == tes.id);
          if (sep && sep.length > 0) dt.merchantName = sep[0].identityName;
          return dt;
        });
      });
    },
    handleSizeChange(val, e) {
      this.size = val;
      this.data();
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    updateDevice(id) {
      this.dialogTitle = "编辑设备";
      this.dialogVisible = true;
      this.form.id = parseInt(id);
      device(this.form.id).then((res) => {
        this.form = res.data;
        this.addressList = [
          res.data.positionProvince,
          res.data.positionCity,
          res.data.positionArea,
        ];
        this.img = true;
      });
    },
    handleDeviceSuccess(res, file) {
      this.form.litimgUrl = res.fileName;
      this.img = true;
    },
    handleqrCodeSuccess(res, file) {
      this.form.qrCodeUrl = res.fileName;
      this.img = true;
    },
    beforeDeviceUpload(file) {
      const isImg = file.type.indexOf("image/") == 0;
      if (!isImg) {
        this.$message.error("图片格式不正确!");
      }
      return isImg;
    },
    handleQuery() {
      if (this.queryParams.address) {
        this.queryParams.positionArea = this.queryParams.address[2];
        this.queryParams.positionCity = this.queryParams.address[1];
        this.queryParams.positionProvince = this.queryParams.address[0];
        this.$delete(this.queryParams, "address");
      }
      this.queryParams.minPutDate = this.date[0];
      this.queryParams.maxPutDate = this.date[1];
      inquire(this.queryParams).then((res) => {
        this.tableData = res.rows;
        for (let i = 0; i < res.rows.length; i++) {
          this.tableData[i].position =
            CodeToText[res.rows[i].positionProvince] +
            "/" +
            CodeToText[res.rows[i].positionCity] +
            "/" +
            CodeToText[res.rows[i].positionArea];
        }
        this.total = parseInt(res.total);
      });
    },
    submmit() {
      const _this = this;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (_this.addressList.length > 0) {
            console.log(_this.addressList);
            this.form.positionArea = _this.addressList[2];
            this.form.positionCity = _this.addressList[1];
            this.form.positionProvince = _this.addressList[0];
          }
          this.$delete(this.form, "positionCityValue");
          this.$delete(this.form, "positionProvinceValue");
          this.$delete(this.form, "statusValue");
          if (this.dialogTitle == "编辑设备") {
            new Promise((resolve, reject) => {
              update(this.form).then((res) => {
                this.dialogVisible = false;
                resolve();
              });
            }).then((res) => {
              this.data();
            });
          } else {
            new Promise((resolve, reject) => {
              add(this.form).then((res) => {
                this.dialogVisible = false;
                resolve();
              });
            }).then((res) => {
              this.data();
            });
          }
        } else {
          return false;
        }
      });
    },
    remove(id) {
      new Promise((resolve, reject) => {
        del(id).then((res) => {
          resolve();
        });
      }).then((res) => {
        this.$message("删除成功");
        this.data();
      });
    },
    reset(code){
      new Promise((resolve, reject) => {
        facilityreset(code).then((res) => {
          resolve();
        });
      }).then((res) => {
        this.$message("清零成功");
        this.data();
      });
    },
    addPrice(row) {
      this.priceTableData.push({ type: null });
      this.priceTableData.sort(function (obj1, obj2) {
        var val1 = obj1.type;
        var val2 = obj2.type;
        if (val1 < val2) {
          return -1;
        } else if (val1 > val2) {
          return 1;
        } else {
          return 0;
        }
      });
      this.priceTableData.forEach((item) => {
        item.facilityCode = this.code;
        this.priceTableData.forEach((item2) => {});
      });
    },
    removePrice(colorId, noColorId, index, itemDefault) {
      if (itemDefault) {
        return this.$message({
          message: "默认价格无法删除!",
          type: "warning",
        });
      }
      if (colorId || noColorId) {
        let ids = [];
        if (colorId != null) {
          ids.push(colorId);
        }
        if (noColorId != null) {
          ids.push(noColorId);
        }
        new Promise((resolve, reject) => {
          delPrintPrice(ids).then((res) => {
            resolve();
          });
        }).then((res) => {
          priceList(this.code).then((res) => {
            this.priceTableData = [{}];
            if (res.rows.length > 0) {
              this.priceTableData = res.rows;
            }
          });
        });
      } else {
        this.priceTableData.splice(index, 1);
      }
    },
    expandSelect(row, expandedRows) {
      var that = this;
      if (expandedRows.length) {
        that.expands = [];
        if (row) {
          that.expands.push(row.id);
        }
      } else {
        that.expands = [];
      }

      if (that.expands.length < 1) {
        return;
      }
      this.code = expandedRows[0].code;
      new Promise((resolve, reject) => {
        priceList(this.code).then((res) => {
          this.priceTableData = [{}];
          if (res.rows.length > 0) {
            this.priceTableData = res.rows;
          } else {
            resolve();
          }
        });
      }).then((res) => {
        defaultPrintingPrice().then((res) => {
          this.priceTableData = res.rows;
          this.priceTableData.forEach((item) => {
            if (item.facilityCode == null) {
              item.facilityCode = this.code;
            }
            if (item.colorId) {
              this.$delete(item, "colorId");
            }
            if (item.noColorId) {
              this.$delete(item, "noColorId");
            }
            if (item.colorPrice == null) {
              item.colorPrice = 0;
            }
            if (item.noColorPrice == null) {
              item.noColorPrice = 0;
            }
            item.default = true;
          });
        });
      });
    },
    submmitPrice() {
      this.priceTableData.forEach((item, index) => {
        item.facilityCode = this.code;
        if (item.default) {
          this.$delete(item, "default");
        }
        this.$delete(item, "typeValue");
      });
      let req = JSON.stringify(this.priceTableData);
      new Promise((resolve, reject) => {
        addPrintPrice(req).then((res) => {
          resolve();
        });
      }).then((res) => {
        this.$message({
          message: "提交成功",
          type: "success",
        });
        priceList(this.code).then((res) => {
          this.priceTableData = [{}];
          if (res.rows.length > 0) {
            this.priceTableData = res.rows;
          }
        });
      });
    },
    objectOneMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const _row = this.setTable(this.priceTableData).one[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
      if (columnIndex === 1) {
        const _row = this.setTable(this.priceTableData).two[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
    },
    setTable(tableData) {
      let spanOneArr = [],
        spanTwoArr = [],
        concatOne = 0,
        concatTwo = 0;
      tableData.forEach((item, index) => {
        if (index === 0) {
          spanOneArr.push(1);
          spanTwoArr.push(1);
        } else {
          if (item.type === tableData[index - 1].type) {
            //第一列需合并相同内容的判断条件
            spanOneArr[concatOne] += 1;
            spanOneArr.push(0);
          } else {
            spanOneArr.push(1);
            concatOne = index;
          }
          tableData.forEach((item1, index1) => {
            if (
              item.paperNumber === item1.paperNumber &&
              item.type === item1.type &&
              index !== index1
            ) {
              tableData.splice(index, 1);
            } else {
              spanTwoArr.push(1);
              concatTwo = index;
            }
          });
        }
      });
      return {
        one: spanOneArr,
        two: spanTwoArr,
      };
    },
    resetQuery() {
      this.queryParams = {};
    },
  },
};
</script>
<style>
.text {
  font-size: 14px;
}
.item {
  margin-bottom: 18px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.box-card {
  margin: 0 auto;
}
.Device-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.Device-uploader .el-upload:hover {
  border-color: #409eff;
}
.Device-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.Device {
  width: 178px;
  height: 178px;
  display: block;
}
.url {
  width: 50px;
  height: 50px;
  display: block;
  margin: 0 auto;
}
</style>
